import { VxeUI } from 'vxe-pc-ui';
import { ElTag } from 'element-plus';

/**
 * 根据提供的选项数据渲染标签
 *
 */
VxeUI.renderer.add('RaLabelOptionRender', {
  renderDefault(renderOpts, params) {
    const { row, column } = params;
    const { props = {} } = renderOpts;

    // 获取 modelValue
    const modelValue = row[column.field];

    // console.log('props.options', props.options);

    // 构建 optionsMap
    const buildOptionsMap = (options) => {
      const map = new Map();
      const flatten = (data) => {
        if (!data) return;
        for (const item of data) {
          map.set(String(item.value), {
            label: item.label,
            tagType: item.tagType,
          });
          if (item.children && item.children.length > 0) {
            flatten(item.children);
          }
        }
      };
      flatten(options);
      return map;
    };

    const optionsMap = buildOptionsMap(props.options || []);

    // 处理 modelValue 逻辑
    let values = [];
    if (modelValue === null || modelValue === undefined || modelValue === '') {
      values = [];
    } else if (Array.isArray(modelValue)) {
      values = modelValue.map(String);
    } else if (typeof modelValue === 'string') {
      values = modelValue
        .split(props.separation || ',')
        .map((v) => v.trim())
        .filter((v) => v);
    } else {
      values = [String(modelValue)];
    }

    // console.log('values', values);

    let labelList = [];
    let singleLabel = '';
    let singleTagType = null;

    if (values.length > 0) {
      const results = values.map((value) => {
        const entry = optionsMap.get(value);
        return entry || { label: value, tagType: 'info' }; // 如果找不到，返回原始值
      });

      if (results.length > 1) {
        labelList = results;
      } else {
        singleLabel = results[0].label;
        singleTagType = results[0].tagType;
      }
    }

    // JSX 渲染
    if (labelList.length > 1) {
      return (
        <>
          {labelList.map((item, index) => (
            <ElTag
              key={index}
              type={item.tagType || props.type || 'primary'}
              class="mr-1"
            >
              {item.label}
            </ElTag>
          ))}
        </>
      );
    } else if (singleLabel) {
      return (
        <ElTag type={singleTagType || props.type || 'primary'}>
          {singleLabel}
        </ElTag>
      );
    } else {
      return <span>{modelValue || '-'}</span>;
    }
  },
});
